package cn.wolfcode.car.service.impl;

import cn.wolfcode.car.domain.Employee;
import cn.wolfcode.car.exception.LoginException;
import cn.wolfcode.car.mapper.EmployeeMapper;
import cn.wolfcode.car.qo.QueryObject;
import cn.wolfcode.car.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void save(Employee employee, Long[] roleIds) {
        Md5Hash md5Hash = new Md5Hash(employee.getPassword(), employee.getUsername(), 3);
        employee.setPassword(md5Hash.toString());
        employeeMapper.insert(employee);
        if(roleIds != null && roleIds.length > 0){
            for (Long roleId : roleIds) {
                employeeMapper.saveRelation(employee.getId(), roleId);
            }
        }
    }

    @Override
    public void delete(Long id) {
        employeeMapper.deleteRelation(id);
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Employee employee, Long[] roleIds) {
        employeeMapper.deleteRelation(employee.getId());
        employeeMapper.updateByPrimaryKey(employee);
        if(roleIds != null && roleIds.length > 0){
            for (Long roleId : roleIds) {
                employeeMapper.saveRelation(employee.getId(), roleId);
            }
        }
    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> selectAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public PageInfo<Employee> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Employee> employees = employeeMapper.selectForList(qo);
        return new PageInfo<>(employees);
    }

    @Override
    public Employee checkEmp(String username, String password) {
        Employee employee = employeeMapper.checkEmp(username);
        if(employee == null){
            throw new LoginException("用户不存在");
        }
        if(!employee.getPassword().equals(password)){
            throw new LoginException("密码错误");
        }
        return employee;
    }

    @Override
    public Employee queryByUsername(String username) {
        return employeeMapper.checkEmp(username);
    }
}
